package com.intct.hbase.dml;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.intct.hbase.HBaseConnection;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.regionserver.IncreasingToUpperBoundRegionSplitPolicy;

import java.io.IOException;
import java.util.Map;

/**
 * @author gufg
 * @since 2025-11-04 09:35
 * // put '命名空间:表名', 'rowkey', '列族:列限定符', '值'
 */
public class PutData {
    public static void main(String[] args) throws IOException {
        // 客户端输入json字符串
        String jsonString = "{\"family\": \"f1\",\"rowkey\": \"1002\",\"data\": {\"name\": \"lisi_3\"}}";

        // 调用JSON.parseObject将json字符串转为JSONObject
        JSONObject jsonObj = JSON.parseObject(jsonString);
        // 根据family、rowkey键获取值
        String family = jsonObj.getString("family");
        String rowkey = jsonObj.getString("rowkey");
        // JSON中还有JSON时，使用getJSONObject获取JSONObject
        JSONObject dataObj = jsonObj.getJSONObject("data");

        // 建立连接
        Connection connection = HBaseConnection.connection;

        // TableName实例
        TableName tableName = TableName.valueOf("intct86", "t2");

        // 获取Admin实例
        Admin admin = connection.getAdmin();

        Table table = null;

        try {
            // 判断表存在时
            if (admin.tableExists(tableName)) {
                // 获取Table实例
                table = connection.getTable(tableName);

                Put put = new Put(rowkey.getBytes());

                for (Map.Entry<String, Object> entry : dataObj.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue().toString();

                    put.addColumn(family.getBytes(), key.getBytes(), value.getBytes());
                }

                // 插入数据
                table.put(put);
            }
        } catch (IOException e) {
            System.out.println("插入数据失败！");
        } finally {
            // 关闭资源
            if (admin != null) {
                admin.close();
            }
            if (table != null) {
                table.close();
            }
        }
    }
}
